<?php
    $DEBUG = false;
    include_once "classes/User.php";
    session_start();
    include_once "session.php";
    if (!isLoggedIn()) {
        exit();
    }
    
    if ($_SESSION['User']->UserType == "Customer") {
        exit();
    }
    
    $DO_GET = $DEBUG;
    $IN = $DO_GET ? $_GET : $_POST;
    include_once "db/db_cse305.php";
    header ("Expires: Sat, 1 Jan 2000 01:00:00 GMT");
    header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header ("Cache-Control: no-cache, must-revalidate");
    header ("Pragma: no-cache");
    if (!isset($IN["t"])) {
        if ($DEBUG)
            echo "'t' not set.<br />";
        exit();
    }
    if (!isset($IN["d"])) {
        if ($DEBUG)
            echo "'d' not set.<br />";
        exit();
    }
    
    $q = $IN["d"];
    if ($q == "") exit();
    if (is_array($q)) {
        exit();
    }
    
    $arr = array();
    $query = null;
    $t = $IN["t"];
    
    $where = "";
    if (isset($IN["l"]) && $IN["l"] == "customer") {
        $where = " && UserType = 'Customer'";
    }
    
    if ($t == "username") {
        $query = sprintf("SELECT * FROM users WHERE UserName LIKE '%%%s%%'".$where." ORDER BY UserId LIMIT 100", mysql_real_escape_string(trim($q)));
    } else if ($t == "id") {
        $query = sprintf("SELECT * FROM users WHERE UserId = '%d'".$where." ORDER BY UserId LIMIT 100", mysql_real_escape_string(trim($q)));
    } else if ($t == "lastname") {
        $query = sprintf("SELECT * FROM users WHERE LastName LIKE '%%%s%%'".$where." ORDER BY UserId LIMIT 100", mysql_real_escape_string(trim($q)));
    }    
    $result = mysql_query($query) or die(mysql_error());
    while ($row = mysql_fetch_array($result)) {
        //<th>User ID</th><th>User Name</th><th>User Type</th><th>First Name</th><th>Last Name</th>
        $user = array();
        $user["UserID"] = $row["UserId"];
        $user["UserName"] = $row["UserName"];
        $user["UserType"] = $row["UserType"];
        $user["FirstName"] = $row["FirstName"];
        $user["LastName"] = $row["LastName"];
        $arr[] = $user;
    }
    mysql_free_result($result);
    header("Content-Type: application/json");
    echo json_encode($arr);
?>
